//group----First group of 6 digits
group = ["LLLLLL", "LLGLGG", "LLGGLG",
    "LLGGGL", "LGLLGG", "LGGLLG",
    "LGGGLL", "LGLGLG", "LGLGGL",
    "LGGLGL"]
//lcode----L - digits
lcode = ["0001101", "0011001", "0010011",
    "0111101", "0100011", "0110001",
    "0101111", "0111011", "0110111",
    "0001011"]
//gcode----G - digits
gcode = ["0100111", "0110011", "0011011",
    "0100001", "0011101", "0111001",
    "0000101", "0010001", "0001001",
    "0010111"]
//rcode----R - digits
rcode = ["1110010", "1100110", "1101100",
    "1000010", "1011100", "1001110",
    "1010000", "1000100", "1001000",
    "1110100"]
function encodeBarcode(digits) {
    var map = {
        'L': (x) => lcode[x],
        'R': (x) => rcode[x],
        'G': (x) => gcode[x]
    }
    var [_, first, left, right] = digits.match(/(\d)(\d{6})(\d{5})$/);
    var odds = [...digits].filter((v, i) => i % 2 === 0);
    var evens = [...digits].filter((v, i) => i % 2);
    var sum = odds.reduce((s, v) => s += +v, 0) + 3 * evens.reduce((s, v) => s += +v, 0);
    var check_digit = (10 - sum % 10);
    if (check_digit === 10) check_digit = 0;
    var g = group[+first];
    var left_code = [...left].map((v, i) => map[g[i]](v)).join('')
    var right_code = [...(right + check_digit)].map(v => rcode[v]).join('');
    return `101${left_code}01010${right_code}101`
}
console.log(encodeBarcode("590123412345"))

